//
//  PlayAudioViewController.m
//  BDD_TWO
//
//  Created by XTW on 2023/6/9.
//

#import "PlayAudioViewController.h"
#import "EZAudioFile.h"
#import "FileManager.h"
#import "CustomSlider.h"
#import "AVPlayerManager.h"
#import "CustomAlertView.h"
#import "RecordEditViewController.h"
#import "RecordViewController.h"
#import "LocalRecordModel.h"

@interface PlayAudioViewController ()<AVPlayerDelegate, UIGestureRecognizerDelegate, UIDocumentInteractionControllerDelegate> {
    BOOL                       _isDragging;
    CGFloat                    angle;
    BOOL                       changeAnimate;
}
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *nameBtn;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalTimeLabel;
@property (weak, nonatomic) IBOutlet UIButton *playBtn;
@property (nonatomic, strong) EZAudioFile *audioFile;
@property (weak, nonatomic) IBOutlet CustomSlider *progressSlider;
@property (weak, nonatomic) IBOutlet UIImageView *loadingImageView;
@property (weak, nonatomic) IBOutlet UIButton *backBtn;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;
@property (strong, nonatomic) UIDocumentInteractionController *documentInteraction;
@property (weak, nonatomic) IBOutlet UIView *bottomView;

@end

@implementation PlayAudioViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"播放";
    [self addBackBtn];
    [((UIButton *)[self addRigthBtn:@"删除"]) addTarget:self action:@selector(deletePress) forControlEvents:UIControlEventTouchUpInside];
    [self initView];
    [self showContent];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [AVPlayerManager manager].delegate = self;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[AVPlayerManager manager] pause];
    self.playBtn.selected = NO;
    [AVPlayerManager manager].delegate = nil;
}

- (void)goBackAction {
    if (self.dismissBack) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        [super goBackAction];
    }
}

- (IBAction)editPress {
    RecordEditViewController *viewCon = [[RecordEditViewController alloc] initWithNibName:@"RecordEditViewController" bundle:nil];
    viewCon.contentArr = [NSArray arrayWithObject:self.model];
    viewCon.SaveHandle = ^{
    };
    CustomNavigationCoutroller *navCon = [[CustomNavigationCoutroller alloc] init];
    navCon.viewControllers = @[viewCon];
    navCon.modalPresentationStyle = UIModalPresentationFullScreen;
    [[UIViewControllerCJHelper findCurrentShowingViewController].navigationController presentViewController:navCon animated:YES completion:nil];
}

- (IBAction)savePress {
    [UserManger saveFile];
    [self goBackAction];
}


- (void)showContent {
    [self trackPlayDidEnd];
    NSString *path = [[FileManager sharedManager] getLocalFilePath:self.model.fileName];
    if ([[FileManager sharedManager] judgeObjectExistence:path] && [[NSData dataWithContentsOfFile:path] length] > 0) {
        self.audioFile = [EZAudioFile audioFileWithURL:[NSURL fileURLWithPath:path]];
    } else {
        self.audioFile = nil;
    }
    [self.nameBtn setTitle:self.model.nickName forState:UIControlStateNormal];
    [self.nameBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -self.nameBtn.imageView.frame.size.width, 0, self.nameBtn.imageView.frame.size.width)];
    [self.nameBtn setImageEdgeInsets:UIEdgeInsetsMake(0, self.nameBtn.titleLabel.bounds.size.width, 0, -self.nameBtn.titleLabel.bounds.size.width - 5)];
    self.totalTimeLabel.text = self.audioFile.formattedDuration;
    [[AVPlayerManager manager] setAVPlayerURL:self.audioFile.url];
    
    NSArray *allFiles = [UserManger currentLoggedInUser].files;
    NSInteger index = [allFiles indexOfObject:self.model];
    if (index == 0) {
        self.backBtn.enabled = NO;
        if (allFiles.count > 1) {
            self.nextBtn.enabled = YES;
        } else {
            self.nextBtn.enabled = NO;
        }
    } else {
        self.backBtn.enabled = YES;
        if (allFiles.count - 1 == index) {
            self.nextBtn.enabled = NO;
        } else {
            self.nextBtn.enabled = YES;
        }
    }
}

- (IBAction)playPress {
    self.playBtn.selected = !self.playBtn.selected;
    if (!self.playBtn.selected) {
        [[AVPlayerManager manager] pause];
        changeAnimate = YES;
    } else {
        [[AVPlayerManager manager] play];
        changeAnimate = NO;
        [self startAnimation];
    }
}

- (IBAction)backPress {
    NSArray *allFiles = [UserManger currentLoggedInUser].files;
    NSInteger index = [allFiles indexOfObject:self.model];
    self.model = [allFiles objectAtIndex:index - 1];
    [self showContent];
    [[AVPlayerManager manager] pause];
}

- (IBAction)nextPress {
    NSArray *allFiles = [UserManger currentLoggedInUser].files;
    NSInteger index = [allFiles indexOfObject:self.model];
    self.model = [allFiles objectAtIndex:index + 1];
    [self showContent];
    [[AVPlayerManager manager] pause];
}

- (void)deletePress {
    CustomAlertView *alertView = [[CustomAlertView alloc] initItem:@"确定要删除该音频？" withButtons:[NSArray arrayWithObjects:@"取消", @"确定", nil]];
    alertView.SureHandle = ^{
        [UserManger removeFileModel:self.model];
        [self showHUDAlert:@"删除成功"];
        [self performSelector:@selector(goBackAction) withObject:self afterDelay:2.0f];
    };
    [alertView backgroundClickDisable];
    [alertView show];
}

- (void)initView {
    [self.scrollView setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - IS_iPhoneX_Top - NavBarHeight - IS_iPhoneX_Bottom - 64)];
    [self.bottomView setFrame:CGRectMake(0, SCREEN_HEIGHT_DEVICE - IS_iPhoneX_Bottom - 44 - 10, SCREEN_WIDTH_DEVICE, 44)];

    [self.scrollView setContentSize:CGSizeMake(0, 634)];
    [self.progressSlider setThumbImage:[UIImage imageNamed:@"slider_dot1"] forState:UIControlStateNormal];
    [self.progressSlider addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
    [self.progressSlider addTarget:self action:@selector(seekTime:) forControlEvents:UIControlEventTouchUpInside];
    [self.progressSlider addTarget:self action:@selector(startSlider:) forControlEvents:UIControlEventTouchDown];
    self.progressSlider.value = 0;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionTapGesture:)];
    tapGesture.delegate = self;
    [self.progressSlider addGestureRecognizer:tapGesture];
}

- (void)startAnimation{
    if (!changeAnimate) {
        changeAnimate = YES;
        CGAffineTransform endAngle = CGAffineTransformMakeRotation(angle * (M_PI /180.0f));
        [UIView animateWithDuration:0.01 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
            self.loadingImageView.transform = endAngle;
        } completion:^(BOOL finished) {
            self->changeAnimate = !finished;
            if (self.playBtn.selected) {
                self->angle += 1.0;
                [self startAnimation];
            }
        }];
    }
}

#pragma mark ---AVPlayerDelegate---
- (void)timeRunAndTime:(double)runTime andValue:(NSString *)value andScale:(CGFloat)scale {
    if (!_isDragging) {
        self.progressSlider.value  = scale;
        self.timeLabel.text = [value substringToIndex:5];
    }
}

- (void)trackPlayDidEnd {
    self.progressSlider.value = 0;
    self.playBtn.selected = NO;
}

# pragma mark - Slider Handle
-(void)valueChanged:(UISlider *)slider {
    if (self.progressSlider.value == 1) {
        self.progressSlider.value = 0;
    }
    NSTimeInterval currentTime = CMTimeGetSeconds([AVPlayerManager manager].currentMusicItem.asset.duration) * self.progressSlider.value;
    self.timeLabel.text = [self timeStringWithTimeInterval:currentTime];

}

/**
 *  拖动到某个时间点播放
 *
 *  @param slider 传入的slider对象
 */
-(void)seekTime:(UISlider *)slider {
    NSTimeInterval currentTime = CMTimeGetSeconds([AVPlayerManager manager].currentMusicItem.asset.duration) * self.progressSlider.value;
    [[AVPlayerManager manager] seekToTimeInterval:currentTime];
    [self performSelector:@selector(endSlider) withObject:self afterDelay:0.5f];
}

-(void)startSlider:(UISlider *)slider{
    NSLog(@"拖动");
    _isDragging = YES;
}

- (void)endSlider {
    _isDragging = NO;
}

- (void)actionTapGesture:(UITapGestureRecognizer *)sender {
    CGPoint touchPoint = [sender locationInView:self.progressSlider];
    CGFloat value = (self.progressSlider.maximumValue - self.progressSlider.minimumValue) * (touchPoint.x / self.progressSlider.frame.size.width );
    [self.progressSlider setValue:value animated:YES];
    NSTimeInterval currentTime = CMTimeGetSeconds([AVPlayerManager manager].currentMusicItem.asset.duration) * self.progressSlider.value;
    self.timeLabel.text = [self timeStringWithTimeInterval:currentTime];

    [[AVPlayerManager manager] seekToTimeInterval:currentTime];
}

- (NSString *)timeStringWithTimeInterval:(NSTimeInterval)time {
    NSInteger hours       = (time / 3600);
    NSInteger min = (NSInteger)(time / 60) % 60;
    NSInteger sec         = (NSInteger)time % 60;
    NSString * timeString = [NSString stringWithFormat:@"%02ld:%02ld",hours*60+min,sec];
    return timeString;
}


- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller {
    return self;
}

- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller {
    return self.view;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller {
    return self.view.frame;
}

#pragma mark - Lazy
- (UIDocumentInteractionController *)documentInteraction{
    if (!_documentInteraction) {
        _documentInteraction = [[UIDocumentInteractionController alloc] init];
        _documentInteraction.delegate = self;
    }
    return _documentInteraction;
}
@end
